<?php
namespace app\control\controller;


use app\common\model\AdminMenuModel;
use app\common\model\AdminUserModel;
use app\common\model\RegionsModel;
use think\Controller;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;

class PublicController extends Controller
{
    public function login()
    {
        $sessionAdminId = Session::get('UID');
        if (!empty($sessionAdminId) && !empty(Cache::get('admin_user'))) {
            $this->redirect(url("index/index"));
        }

        return $this->fetch();
    }

    /**
     * 从图片文件创建Image资源
     * @param $file 图片文件，支持url
     * @return bool|resource    成功返回图片image资源，失败返回false
     */

    function createImageFromFile($file){
        if(preg_match('/http(s)?:\/\//',$file)){
            $fileSuffix = getNetworkImgType($file);
        }else{
            $fileSuffix = pathinfo($file, PATHINFO_EXTENSION);
        }

        if(!$fileSuffix) return false;
        switch ($fileSuffix){
            case 'jpeg':
                $theImage = @imagecreatefromjpeg($file);
                break;
            case 'jpg':
                $theImage = @imagecreatefromjpeg($file);
                break;
            case 'png':
                $theImage = @imagecreatefrompng($file);
                break;
            case 'gif':
                $theImage = @imagecreatefromgif($file);
                break;
            default:
                $theImage = @imagecreatefromstring(file_get_contents($file));
                break;
        }
        return $theImage;
    }

    /**
     * 分行连续截取字符串
     * @param $str  需要截取的字符串,UTF-8
     * @param int $row  截取的行数
     * @param int $number   每行截取的字数，中文长度
     * @param bool $suffix  最后行是否添加‘...’后缀
     * @return array    返回数组共$row个元素，下标1到$row
     */

    function cn_row_substr($str,$row = 1,$number = 10,$suffix = true){
        $result = array();
        for ($r=1;$r<=$row;$r++){
            $result[$r] = '';
        }

        $str = trim($str);
        if(!$str) return $result;
        $theStrlen = strlen($str);

        //每行实际字节长度
        $oneRowNum = $number * 3;
        for($r=1;$r<=$row;$r++){
            if($r == $row and $theStrlen > $r * $oneRowNum and $suffix){
                $result[$r] = $this->mg_cn_substr($str,$oneRowNum-6,($r-1)* $oneRowNum).'...';
            }else{
                $result[$r] = $this->mg_cn_substr($str,$oneRowNum,($r-1)* $oneRowNum);
            }
            if($theStrlen < $r * $oneRowNum) break;
        }
        return $result;
    }

    /**
     * 按字节截取utf-8字符串
     * 识别汉字全角符号，全角中文3个字节，半角英文1个字节
     * @param $str  需要切取的字符串
     * @param $len  截取长度[字节]
     * @param int $start    截取开始位置，默认0
     * @return string
     */

    function mg_cn_substr($str,$len,$start = 0){
        $q_str = '';
        $q_strlen = ($start + $len)>strlen($str) ? strlen($str) : ($start + $len);

        //如果start不为起始位置，若起始位置为乱码就按照UTF-8编码获取新start
        if($start and json_encode(substr($str,$start,1)) === false){
            for($a=0;$a<3;$a++){
                $new_start = $start + $a;
                $m_str = substr($str,$new_start,3);
                if(json_encode($m_str) !== false) {
                    $start = $new_start;
                    break;
                }
            }
        }

        //切取内容
        for($i=$start;$i<$q_strlen;$i++){
            //ord()函数取得substr()的第一个字符的ASCII码，如果大于0xa0的话则是中文字符
            if(ord(substr($str,$i,1))>0xa0){
                $q_str .= substr($str,$i,3);
                $i+=2;
            }else{
                $q_str .= substr($str,$i,1);
            }
        }
        return $q_str;
    }

    /**
     * 用户登陆
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function rel_login(){
        $username=Request::post('username');
        $pwd=Request::post('password');

        $info=AdminUserModel::check_login($username,$pwd);

        if($info['status']){
            $uid=$info['data']['id'];
            Session::set('UID',$uid);
            Cache::set("admin_user",$info["data"],3600*2);

            //更新登陆信息
            $au=AdminUserModel::get($uid);
            $au->last_login_ip=request()->ip(0,true);
            $au->last_login_time=time();
            $au->save();

            //更新菜单
            AdminMenuModel::getMenu(1,$au);

            $this->success('登陆成功！',url('index/index'));
        }else{
            $this->error($info['msg']);
        }
    }

    /**
     * 用户登出
     */
    public function logout()
    {
        Session::delete('UID');
        Cache::rm('admin_user');

        return $this->redirect(url("public/login"));
    }

    /**
     * @param string $province 省
     * @param string $city 市
     * @param string $area 县
     * @param int $type 类型，不同的样式（备用）
     * @return mixed
     */
    public function regions($type=0,$province='',$city='',$area=''){

        if(Request::isAjax()){
//            $pid=Request::param('pid');
//            $list=RegionsModel::getAll($pid);
            $list=RegionsModel::getRegionDate();
            return $list;
        }else{
            $this->assign('province',$province);
            $this->assign('city',$city);
            $this->assign('area',$area);
            $this->assign('type',$type);

            $provinces=RegionsModel::getAll();
            $this->assign('provinces',$provinces);

            //return $this->view->fetch('Public/regions');
            return View::fetch('public/regions');
        }
    }

    /**
     * 获取编辑器
     * @param string $content 内容
     * @param string $name 字段名
     * @param string $height 高度
     * @return string
     */
    public function ueditor($content='',$name='content',$height="800"){

        $this->assign('name',$name);
        $this->assign('height',$height);
        $this->assign('content',$content);

        return View::fetch('public/ueditor');
    }

    /**
     * 获取后台图片上传插件
     * @param string $url 图片地址
     * @param string $name 字段名
     * @return string
     */
    public function uploadImage($url='',$name='thumb',$title="上传图片"){

        $this->assign('name',$name);
        $this->assign('url',$url);
        $this->assign('title',$title);
        $this->assign('Upurl',url('File/upload'));

        return View::fetch('public/upload_image');
    }

    /**
     * 获取前台图片上传插件
     * @param string $url 图片地址
     * @param string $name 字段名
     * @return string
     */
    public function getFundImg($url='',$name='thumb',$title="上传图片"){

        $this->assign('name',$name);
        $this->assign('url',$url);
        $this->assign('title',$title);
        $this->assign('Upurl',url('File/userUpload'));

        return View::fetch('public/upload_image');
    }

    /**
     * 清除所有缓存
     */
    public function clear_all() {
        $CACHE_PATH = config('cache.runtime_path').'/cache/';
        $TEMP_PATH = config('cache.runtime_path').'/temp/';
        $LOG_PATH = config('cache.runtime_path').'/log/';
        if (delete_dir_file($CACHE_PATH) && delete_dir_file($TEMP_PATH) && delete_dir_file($LOG_PATH)) {
            $this->success('清除缓存成功!');
        } else {
            $this->error('清除缓存失败!');
        }
    }

    /**
     * 跳转提示
     */
    public function jump(Request $request){
        $data=Request::param();

        if($request::isAjax()){
            return $data;
        }

        $this->assign('url',$data['url']);
        $this->assign('wait',$data['wait']);
        $this->assign('msg',$data['msg']);
        $this->assign('code',$data['code']);
        return $this->fetch();
    }
}
